'use strict';

exports.main = async (event, context) => {
  console.log('获取通知消息云函数被调用，参数:', event)
  
  const { userId, limit = 50, skip = 0, type } = event
  
  if (!userId) {
    return {
      success: false,
      code: 400,
      msg: '缺少用户ID参数'
    }
  }

  const db = uniCloud.database()
  
  try {
    console.log(`开始查询用户 ${userId} 的通知消息`)
    
    // 构建查询条件
    let whereCondition = {
      user_id: userId,
      status: db.command.neq('deleted') // 排除已删除的通知
    }
    
    // 如果指定了类型，添加类型过滤
    if (type) {
      whereCondition.type = type
    }
    
    console.log('查询条件:', whereCondition)
    
    // 查询通知消息
    const result = await db.collection('notification-messages')
      .where(whereCondition)
      .orderBy('create_time', 'desc') // 按创建时间倒序
      .skip(skip)
      .limit(limit)
      .get()
    
    console.log(`查询到 ${result.data.length} 条通知消息`)
    
    // 处理查询结果
    const notifications = result.data.map(item => {
      return {
        _id: item._id,
        user_id: item.user_id,
        type: item.type,
        category: item.category,
        title: item.title,
        content: item.content,
        related_id: item.related_id,
        related_type: item.related_type,
        priority: item.priority,
        is_read: item.is_read || false,
        read_time: item.read_time,
        action_url: item.action_url,
        action_text: item.action_text,
        create_time: item.create_time,
        expire_time: item.expire_time,
        status: item.status || 'active'
      }
    })
    
    console.log('处理后的通知数据:', notifications.length, '条')
    
    return {
      success: true,
      code: 200,
      msg: '获取通知消息成功',
      data: notifications
    }
    
  } catch (error) {
    console.error('获取通知消息失败:', error)
    return {
      success: false,
      code: 500,
      msg: '获取通知消息失败: ' + error.message,
      error: error.toString()
    }
  }
}
